//
//  StockListController.m
//  Stock
//
//  Created by blacksun on 11-6-11.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "StockListController.h"


@implementation StockListController
@synthesize imageScrollView;
@synthesize childScrollView;
@synthesize childViewController;
@synthesize pageControll;
@synthesize scrollContainer;
@synthesize myStock;
@synthesize parentController;
@synthesize imageViewController;
@synthesize leftOffsetImgaeView;
@synthesize rightOffsetImageView;
@synthesize stockSection;
@synthesize lastedChildView;
@synthesize selectedImageView;
@synthesize priceLabel;
@synthesize changeRateLabel;
@synthesize myStockService;



-(void)requestFinishedWithResult:(id)aResult andUserinfo:(NSDictionary *)aUserinfo{
    NSString *action = [aUserinfo objectForKey:kASIHttpRequestUserinfoKey];
    NSLog(@"ssdfs");
    if ([action isEqualToString:kMyStockServiceUpdateStock]) {
        self.myStock = [aResult objectAtIndex:0];
        self.priceLabel.text = [myStock.closingPrice stringValue];
        if ([myStock.changedRate hasPrefix:@"-"]) {
            changeRateLabel.textColor = [UIColor greenColor];
            self.changeRateLabel.text = myStock.changedRate;
        }else{
            changeRateLabel.textColor = [UIColor redColor];
            changeRateLabel.text = [NSString stringWithFormat:@"+%@",myStock.changedRate];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:kUpdateStockNotification object:nil];
    }
}


-(void)childViewDidUpdated:(float)viewHeight{
    CGRect frame = lastedChildView.frame;
    self.scrollContainer.contentSize = CGSizeMake(320.0, frame.origin.y+viewHeight);
    lastedChildView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, viewHeight);
}

-(void)didClikedStockChildSegment:(id)sender{
    UIButton *button = (UIButton *)sender;
    if (button.tag == selectedChildIndex) {
        return;
    }
    UIView *unreadImage = [self.view viewWithTag:100+button.tag];
    unreadImage.hidden = YES;
    
    selectedChildIndex = button.tag;
    
    [self.lastedChildView removeFromSuperview];
    self.lastedChildView = nil;
    self.childViewController = nil;
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDelay:0.3];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    self.selectedImageView.frame = CGRectMake(selectedChildIndex*100.0+10.0, 5.0, 100.0, 30.0);
    [UIView commitAnimations];
    
    NSArray *stockChildren = [stockSection objectForKey:kStockChilren];
    NSDictionary *stockChildDict = [stockChildren objectAtIndex:button.tag];
    Class clazz = NSClassFromString([stockChildDict objectForKey:kStockChildController]);
    NSString *xibName = [stockChildDict objectForKey:kStockChildXib];
    if ([xibName length] == 0) {
        self.childViewController = [[[clazz alloc] initWithStyle:UITableViewStylePlain] autorelease];
        NSString *stockChildId = [stockChildDict objectForKey:kStockChildId];
        childViewController.sectionId = stockChildId;
        childViewController.stockId = myStock.uuid;
        int sectionIndex = 0;
        if ([stockChildId isEqualToString:@"CR"]) {
            sectionIndex = myStock.cr;
        }else if ([stockChildId isEqualToString:@"CN"]) {
            sectionIndex = myStock.cn;
        }else if ([stockChildId isEqualToString:@"MH"]) {
            sectionIndex = myStock.mh;
        }
        childViewController.sectionIndex = sectionIndex;
        childViewController.parentController = self;
        childViewController.view.frame = CGRectMake(0.0, 160.0, 320.0, 256.0);
        
    }else{
        self.childViewController = [[[clazz alloc] initWithNibName:xibName bundle:nil] autorelease];
        childViewController.parentController = self;
        [childViewController performSelector:@selector(setMyStock:) withObject:myStock];
        CGRect frame = childViewController.view.frame;
        childViewController.view.frame = CGRectMake(0.0, 160.0, frame.size.width,frame.size.height);
    }
    [self.scrollContainer addSubview:childViewController.view];
    self.lastedChildView = childViewController.view;
}


-(void)addToFavorite{
    if (![[StockAppHelper shareInstance] canAddFavoriteStock]) {
        return;
    }
    [myStock save];
    NSLog(@"add=%@",myStock.uuid);
    [myStockService addMyStockWithIds:myStock.uuid];
    [StockContext shareInstance].isFavorite = YES;
    
    self.navigationItem.rightBarButtonItem = nil;
    [[StockAppHelper shareInstance] setupAddFavoriteNotify];
}

- (void)dealloc{
    self.imageScrollView = nil;
    self.childViewController = nil;
    self.childScrollView = nil;
    self.pageControll = nil;
    self.scrollContainer = nil;
    self.myStock = nil;
    self.imageViewController = nil;
    self.leftOffsetImgaeView = nil;
    self.rightOffsetImageView = nil;
    self.stockSection = nil;
    self.lastedChildView = nil;
    self.selectedImageView = nil;
    [StockContext shareInstance].isFavorite = NO;
    self.priceLabel = nil;
    self.changeRateLabel = nil;
    [self.myStockService cancleAllRequest];
    self.myStockService = nil;
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - UISrollView Delegate
-(void)setUpImageViewController:(int)index{
    if (index<0 || index>=[parentController.localStocks count]) {
        return;
    }
    if ([[imageViewController objectAtIndex:index] isEqual:[NSNull null]]) {
        NowChartViewController *imageChild = [[NowChartViewController alloc] initWithNibName:@"NowChartViewController" bundle:nil];
        imageChild.index = index;
        imageChild.currentMyStock = [parentController.localStocks objectAtIndex:index];
        [self.imageScrollView addSubview:imageChild.view];
        [imageViewController insertObject:imageChild atIndex:index];
        [imageChild release];
    }
}
-(void)setPageControlPageNumber:(BOOL)isPrev currentPage:(int)page{
    int index = page%9;
    if (pageControll.numberOfPages < kMaxPageControlPages) {
        pageControll.currentPage = page;
    }else if(index>2 && index<6 ){
        pageControll.currentPage = index;
    }else if (isPrev) {
        if (pageControll.currentPage == 0) {
            
        }else if (pageControll.currentPage>2) {
            pageControll.currentPage = pageControll.currentPage-1;
        }else if (page>2) {
            pageControll.currentPage = pageControll.currentPage-1;
            [self performSelector:@selector(setPageControlNumber:) withObject:[NSNumber numberWithInt:pageControll.currentPage+1] afterDelay:0.3];
        }else{
            pageControll.currentPage = page;
        }
    }else{
        if (pageControll.currentPage == (kMaxPageControlPages-1)) {
        }else if ([parentController.localStocks count]-1-page < 3) {
            pageControll.currentPage = kMaxPageControlPages-1 - ([parentController.localStocks count]-1-page);
        }else if(pageControll.currentPage<6){
            pageControll.currentPage = pageControll.currentPage + 1;
        }else{
            pageControll.currentPage = pageControll.currentPage + 1;
            [self performSelector:@selector(setPageControlNumber:) withObject:[NSNumber numberWithInt:pageControll.currentPage-1] afterDelay:0.3];
        }
    }
}
-(void)setPageControlNumber:(NSNumber *)number{
    pageControll.currentPage = [number intValue];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)aScrollView{
    if (aScrollView == self.childScrollView) {
        return;
    }
    CGFloat pageWidth = aScrollView.frame.size.width;
    int page = floor((aScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    self.pageControll.currentPage = page;
    [[self.imageViewController objectAtIndex:page] chartViewDidDisplay];
}
- (void)scrollViewDidScroll:(UIScrollView *)aScrollView{
    if (aScrollView == imageScrollView) {
        return;
    }
    float offsetX = aScrollView.contentOffset.x;
    if (offsetX > 0) {
        leftOffsetImgaeView.hidden = NO;
    }else{
        leftOffsetImgaeView.hidden = YES;
    }
    if (offsetX>180.0) {
        rightOffsetImageView.hidden = YES;
    }else{
        rightOffsetImageView.hidden = NO;
    }
}


#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = myStock.name;
    self.myStockService = [[[MyStockService alloc] initWithDelegate:self] autorelease];
    
    
    selectedChildIndex = UINT_MAX;
    self.imageViewController = [NSMutableArray array];
    
    StockAppDelegate *delegate = [UIApplication sharedApplication].delegate;
    NSDictionary *stockDict = [delegate.stockSections objectAtIndex:3];
    self.stockSection = stockDict;
    NSArray *children = [stockSection objectForKey:kStockChilren];
    for (int i=0; i<[children count];i++) {
        NSDictionary *stockChild = [children objectAtIndex:i];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(100.0*i+10.0, 0.0, 100.0, 40.0);
        [button setTitle:[stockChild objectForKey:kStockChildName] forState:UIControlStateNormal];
        button.tag = i;
        [button addTarget:self action:@selector(didClikedStockChildSegment:) forControlEvents:UIControlEventTouchUpInside];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100.0*i+95.0, 5.0, 15.0, 15.0)];
        imageView.tag = 100+i;
        
        NSString *childId = [stockChild objectForKey:kStockChildId];
        int tempAmount = 0;
        if ([@"CR" isEqualToString:childId]) {
            tempAmount = myStock.crDifference;
        }else if([@"MH" isEqualToString:childId]){
            tempAmount = myStock.mhDifference;
        }else if([@"CN" isEqualToString:childId]){
            tempAmount = myStock.cnDifference;
        }
        int amount = tempAmount>9 ? 9 : tempAmount;
        imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"red_%d.png",amount]];
        [self.childScrollView addSubview:button];
        [self.childScrollView addSubview:imageView];
        [imageView release];
    }
    [self.childScrollView setContentSize:CGSizeMake([children count]*100.0+20.0, 40.0)];
    self.childScrollView.delegate = self;
    
    //set current stock is in favorite?
    [StockContext shareInstance].isFavorite = [myStock countByUUID]==0?NO:YES;
    
    
    if (![StockContext shareInstance].isFavorite) {
        UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"添加到自选" style:UIBarButtonItemStyleBordered target:self action:@selector(addToFavorite)];
        self.navigationItem.rightBarButtonItem = rightButton;
        [rightButton release];
    }
    KChartViewController *imageChild1 = [[KChartViewController alloc] initWithNibName:@"KChartViewController" bundle:nil];
    imageChild1.chartType = @"tq";
    imageChild1.stockId = myStock.uuid;
    imageChild1.view.frame = CGRectMake(0.0, 0.0, 320.0, 120.0);
    [self.imageScrollView insertSubview:imageChild1.view belowSubview:self.changeRateLabel];
    [imageViewController addObject:imageChild1];
    [imageChild1 performSelector:@selector(chartViewDidDisplay) withObject:nil afterDelay:0.5];
    [imageChild1 performSelector:@selector(release) withObject:nil afterDelay:1.0];    
    KChartViewController *imageChild2 = [[KChartViewController alloc] initWithNibName:@"KChartViewController" bundle:nil];
    imageChild2.chartType = @"dq";
    imageChild2.stockId = myStock.uuid;
    imageChild2.view.frame = CGRectMake(320.0, 0.0, 320.0, 120.0);
    [self.imageScrollView addSubview:imageChild2.view];
    [imageViewController addObject:imageChild2];
    [imageChild2 release];
    
    [self.imageScrollView setContentSize:CGSizeMake(640.0, 120.0)];
    self.imageScrollView.delegate = self;
    self.pageControll.numberOfPages = 2;
    self.pageControll.currentPage = 0;
    
    [self didClikedStockChildSegment:nil];//default to load fist child;
    
    //更新股票信息，包括价格和涨幅
    [myStockService updateMyStocks:[NSArray arrayWithObject:myStock]];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [self.childViewController viewDidUnload];
    self.imageScrollView = nil;
    self.childScrollView = nil;
    self.pageControll = nil;
    self.scrollContainer = nil;
    self.leftOffsetImgaeView = nil;
    self.rightOffsetImageView = nil;
    self.lastedChildView = nil;
    self.selectedImageView = nil;
    self.priceLabel = nil;
    self.changeRateLabel = nil;
    [self.myStockService cancleAllRequest];
    self.myStockService = nil;

}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [childViewController viewDidAppear:animated];
}
-(void)viewWillAppear:(BOOL)animated{
    //NSLog(@"stockview will appear");
    [super viewWillAppear:animated];
    [childViewController viewWillAppear:animated];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [childViewController viewWillDisappear:animated];
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [childViewController viewDidDisappear:animated];
}


@end